package com.itheima.project.face.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.project.constant.security.CustomerCacheConstant;
import com.itheima.project.constant.security.RoleCacheConstant;
import com.itheima.project.core.enums.security.RoleEnum;
import com.itheima.project.exception.ProjectException;
import com.itheima.project.face.RoleFace;
import com.itheima.project.pojo.Role;
import com.itheima.project.service.IRoleResourceService;
import com.itheima.project.service.IRoleService;
import com.itheima.project.utils.BeanConv;
import com.itheima.project.utils.EmptyUtil;
import com.itheima.project.utils.ExceptionsUtil;
import com.itheima.project.vo.security.RoleVo;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @ClassName RoleFaceImpl.java
 * @Description 角色服务实现
 */
@Slf4j
@Component
public class RoleFaceImpl implements RoleFace {

    @Autowired
    IRoleService roleService;

    @Autowired
    IRoleResourceService roleResourceService;

    @Override
    @Cacheable(value = RoleCacheConstant.PAGE,key ="#pageNum+'-'+#pageSize+'-'+#roleVo.hashCode()")
    public Page<RoleVo> findRoleVoPage(RoleVo roleVo,
                                       int pageNum,
                                       int pageSize) throws ProjectException {
        try {
            Page<Role> page = roleService.findRoleVoPage(roleVo, pageNum, pageSize);
            Page<RoleVo> pageVo = BeanConv.toPage(page,RoleVo.class);
            List<RoleVo> roleVoList = pageVo.getRecords();
            if (!EmptyUtil.isNullOrEmpty(roleVoList)){
                roleVoList.forEach(n->{
                    List<String> resourceIdList = roleResourceService.findResourceIdByRoleId(n.getId());
                    String[] resourceIds = new String[resourceIdList.size()];
                    resourceIdList.toArray(resourceIds);
                    n.setHasResourceIds(resourceIds);
                });
            }
            pageVo.setRecords(roleVoList);
            return pageVo;
        } catch (Exception e) {
            log.error("查询角色列表异常：{}", ExceptionsUtil.getStackTraceAsString(e));
            throw new ProjectException(RoleEnum.PAGE_FAIL);
        }

    }

    @Override
    @Caching(evict = {@CacheEvict(value = RoleCacheConstant.PAGE,allEntries = true),
        @CacheEvict(value = RoleCacheConstant.LIST,allEntries = true)},
        put={@CachePut(value =RoleCacheConstant.BASIC,key = "#result.id")})
    @Transactional
    public RoleVo createRole(RoleVo roleVo) throws ProjectException{
        try {
            return BeanConv.toBean(roleService.createRole(roleVo),RoleVo.class);
        } catch (Exception e) {
            log.error("保存角色异常：{}", ExceptionsUtil.getStackTraceAsString(e));
            throw new ProjectException(RoleEnum.CREATE_FAIL);
        }

    }

    @Override
    @Caching(evict = {@CacheEvict(value = RoleCacheConstant.PAGE,allEntries = true),
        @CacheEvict(value = CustomerCacheConstant.ROLES,allEntries = true),
        @CacheEvict(value = RoleCacheConstant.LIST,allEntries = true),
        @CacheEvict(value = RoleCacheConstant.BASIC,key = "#roleVo.id")})
    @Transactional
    public Boolean updateRole(RoleVo roleVo) throws ProjectException{
        try {
            return roleService.updateRole(roleVo);
        } catch (Exception e) {
            log.error("修改角色异常：{}", ExceptionsUtil.getStackTraceAsString(e));
            throw new ProjectException(RoleEnum.UPDATE_FAIL);
        }
    }

    @Override
    @Caching(evict = {@CacheEvict(value = RoleCacheConstant.PAGE,allEntries = true),
        @CacheEvict(value = CustomerCacheConstant.ROLES,allEntries = true),
        @CacheEvict(value = RoleCacheConstant.LIST,allEntries = true)})
    @Transactional
    public Boolean deleteRole(String[] checkedIds)throws ProjectException {
        try {
            return roleService.deleteRole(checkedIds);
        } catch (Exception e) {
            log.error("删除角色异常：{}", ExceptionsUtil.getStackTraceAsString(e));
            throw new ProjectException(RoleEnum.DELETE_FAIL);
        }
    }

    @Override
    public List<RoleVo> initRoleIdOptions()throws ProjectException {
        try {
            List<Role> roles = roleService.initRoleIdOptions();
            return BeanConv.toBeanList(roles,RoleVo.class);
        } catch (Exception e) {
            log.error("删除角色异常：{}", ExceptionsUtil.getStackTraceAsString(e));
            throw new ProjectException(RoleEnum.INIT_ROLEID_OPTIONS_FAIL);
        }
    }
}
